<?php
class Answer {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 获取回答列表（分页）
     */
    public function list(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取分页参数
            $page = max(1, intval($_GET['page'] ?? 1));
            $pageSize = min(50, max(1, intval($_GET['pageSize'] ?? 20)));
            $offset = ($page - 1) * $pageSize;

            // 构建查询条件
            $where = ["qn.user_id = :user_id"];
            $params = [':user_id' => $userId];
            
            // 添加筛选条件
            if (!empty($_GET['questionnaire_id'])) {
                $where[] = "a.questionnaire_id = :questionnaire_id";
                $params[':questionnaire_id'] = $_GET['questionnaire_id'];
            }

            $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

            // 查询总数
            $countStmt = $this->conn->prepare("
                SELECT COUNT(*) 
                FROM answers a
                JOIN questionnaires qn ON a.questionnaire_id = qn.id
                {$whereClause}
            ");
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            // 查询数据
            $query = "
                SELECT 
                    a.id, a.questionnaire_id, qn.title as questionnaire_title,
                    a.respondent_ip, a.created_at,
                    (SELECT GROUP_CONCAT(ad.answer_content SEPARATOR ' & ')
                     FROM answer_details ad
                     JOIN questions q ON ad.question_id = q.id
                     WHERE ad.answer_id = a.id AND q.is_name = 1) as respondent_name
                FROM answers a
                JOIN questionnaires qn ON a.questionnaire_id = qn.id
                {$whereClause}
                ORDER BY a.created_at DESC
                LIMIT :offset, :limit
            ";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            $stmt->execute();
            $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 处理respondent_name为NULL的情况
            foreach ($list as &$item) {
                if (empty($item['respondent_name'])) {
                    $item['respondent_name'] = '匿名用户';
                }
            }

            // 返回列表数据
            echo json_encode([
                'code' => 200,
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'total' => $total,
                        'page' => $page,
                        'pageSize' => $pageSize,
                        'totalPages' => ceil($total / $pageSize)
                    ]
                ]
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

 /**
 * 获取回答详情（修复重复问题和缺失问题）
 */
public function detail(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        if (empty($_GET['id'])) {
            throw new Exception("缺少回答ID参数", 400);
        }

        $answerId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
        if ($answerId === false || $answerId <= 0) {
            throw new Exception("回答ID必须是正整数", 400);
        }

        // 获取回答基本信息
        $answer = $this->getAnswer($answerId, $userId);
        if (!$answer) {
            throw new Exception("回答不存在或无权查看", 404);
        }

        // 获取回答详情 - 使用DISTINCT避免重复
        $stmt = $this->conn->prepare("
            SELECT DISTINCT
                ad.question_id, q.content as question_text, 
                q.type as question_type, q.options as question_options,
                ad.answer_content,
                q.is_name, q.is_date
            FROM answer_details ad
            JOIN questions q ON ad.question_id = q.id
            WHERE ad.answer_id = :answer_id
            ORDER BY q.sort_order ASC
        ");
        $stmt->execute([':answer_id' => $answerId]);
        $details = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 检查是否获取到数据
        if (empty($details)) {
            throw new Exception("未找到回答详情", 404);
        }

        // 处理选择题的选项值
        $processedDetails = [];
        foreach ($details as $detail) {
            if (in_array($detail['question_type'], ['radio', 'check']) && !empty($detail['question_options'])) {
                $options = json_decode($detail['question_options'], true);
                if ($options) {
                    if ($detail['question_type'] === 'radio') {
                        $detail['answer_content'] = $options[$detail['answer_content']] ?? $detail['answer_content'];
                    } else {
                        $selectedOptions = explode(',', $detail['answer_content']);
                        $translatedOptions = [];
                        foreach ($selectedOptions as $option) {
                            $translatedOptions[] = $options[$option] ?? $option;
                        }
                        $detail['answer_content'] = implode(', ', $translatedOptions);
                    }
                }
            }
            $processedDetails[] = $detail;
        }

        // 获取回答者名称
        $respondentNameParts = [];
        foreach ($processedDetails as $detail) {
            if ($detail['is_name']) {
                $respondentNameParts[] = $detail['answer_content'];
            }
        }

        // 返回结果
        echo json_encode([
            'code' => 200,
            'data' => [
                'answer' => $answer,
                'details' => $processedDetails,
                'title' => empty($respondentNameParts) ? '匿名用户' : implode(' & ', $respondentNameParts) . ' - ' . $answer['questionnaire_title']
            ]
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'msg' => $e->getMessage(),
            'data' => null
        ]);
    }
}


    /**
     * 导出回答为Excel
     */
    public function export(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['id'])) {
                throw new Exception("缺少回答ID参数", 400);
            }

            $answerId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
            if ($answerId === false || $answerId <= 0) {
                throw new Exception("回答ID必须是正整数", 400);
            }

            // 获取回答详情
            $detailData = $this->detailInternal($answerId, $userId);
            if (!$detailData) {
                throw new Exception("回答不存在或无权查看", 404);
            }

            $answer = $detailData['answer'];
            $details = $detailData['details'];
            $title = $detailData['title'];

            // 创建Excel文件
            require_once 'vendor/autoload.php';
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // 设置标题
            $sheet->setTitle('回答详情');
            $sheet->mergeCells('A1:D1');
            $sheet->setCellValue('A1', $title);
            $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);

            // 添加回答基本信息
            $sheet->setCellValue('A3', '回答ID:');
            $sheet->setCellValue('B3', $answer['id']);
            $sheet->setCellValue('A4', '问卷标题:');
            $sheet->setCellValue('B4', $answer['questionnaire_title']);
            $sheet->setCellValue('A5', 'IP地址:');
            $sheet->setCellValue('B5', $answer['respondent_ip']);
            $sheet->setCellValue('A6', '回答时间:');
            $sheet->setCellValue('B6', $answer['created_at']);

            // 解析respondent_info
            $respondentInfo = json_decode($answer['respondent_info'], true);
            if ($respondentInfo) {
                $sheet->setCellValue('A7', '用户代理:');
                $sheet->setCellValue('B7', $respondentInfo['user_agent'] ?? '');
                $sheet->setCellValue('A8', '来源页面:');
                $sheet->setCellValue('B8', $respondentInfo['referer'] ?? '');
            }

            // 添加回答详情表头
            $sheet->setCellValue('A10', '问题ID');
            $sheet->setCellValue('B10', '问题内容');
            $sheet->setCellValue('C10', '问题类型');
            $sheet->setCellValue('D10', '回答内容');
            $sheet->getStyle('A10:D10')->getFont()->setBold(true);

            // 添加回答详情数据
            $row = 11;
            foreach ($details as $detail) {
                $sheet->setCellValue('A' . $row, $detail['question_id']);
                $sheet->setCellValue('B' . $row, $detail['question_text']);
                $sheet->setCellValue('C' . $row, $detail['question_type']);
                $sheet->setCellValue('D' . $row, $detail['answer_content']);
                $row++;
            }

            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(10);
            $sheet->getColumnDimension('B')->setWidth(40);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(40);

            // 输出Excel文件
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');

            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
            exit;

        } catch (Exception $e) {
            throw $e;
        }
    }
    /**
 * 导出回答为CSV（公开接口，无需权限验证）
 */
public function exportCSV(): void {
    try {
        if (empty($_GET['id'])) {
            throw new Exception("缺少回答ID参数", 400);
        }

        $answerId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
        if ($answerId === false || $answerId <= 0) {
            throw new Exception("回答ID必须是正整数", 400);
        }

        // 获取回答基本信息
        $stmt = $this->conn->prepare("
            SELECT 
                a.id, a.questionnaire_id, qn.title as questionnaire_title,
                a.respondent_ip, a.created_at
            FROM answers a
            JOIN questionnaires qn ON a.questionnaire_id = qn.id
            WHERE a.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $answerId]);
        $answer = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$answer) {
            throw new Exception("回答不存在", 404);
        }

        // 获取回答详情 - 使用DISTINCT避免重复
        $stmt = $this->conn->prepare("
            SELECT DISTINCT
                ad.question_id, q.content as question_text, 
                q.type as question_type, q.options as question_options,
                ad.answer_content,
                q.is_name, q.is_date
            FROM answer_details ad
            JOIN questions q ON ad.question_id = q.id
            WHERE ad.answer_id = :answer_id
            ORDER BY q.sort_order ASC
        ");
        $stmt->execute([':answer_id' => $answerId]);
        $details = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($details)) {
            throw new Exception("未找到回答详情", 404);
        }

        // 处理选择题的选项值
        $processedDetails = [];
        foreach ($details as $detail) {
            if (in_array($detail['question_type'], ['radio', 'check']) && !empty($detail['question_options'])) {
                $options = json_decode($detail['question_options'], true);
                if ($options) {
                    if ($detail['question_type'] === 'radio') {
                        $detail['answer_content'] = $options[$detail['answer_content']] ?? $detail['answer_content'];
                    } else {
                        $selectedOptions = explode(',', $detail['answer_content']);
                        $translatedOptions = [];
                        foreach ($selectedOptions as $option) {
                            $translatedOptions[] = $options[$option] ?? $option;
                        }
                        $detail['answer_content'] = implode(', ', $translatedOptions);
                    }
                }
            }
            $processedDetails[] = $detail;
        }

        // 生成标题（从is_name字段获取）
        $respondentNameParts = [];
        foreach ($processedDetails as $detail) {
            if ($detail['is_name']) {
                $respondentNameParts[] = $detail['answer_content'];
            }
        }
        $title = '回答_' . $answerId . '_' . 
                (empty($respondentNameParts) ? '匿名用户' : implode('_', $respondentNameParts));
        $title = preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '_', $title);

        // 设置CSV头
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $title . '.csv"');
        
        // 打开输出流
        $output = fopen('php://output', 'w');
        
        // 写入BOM头（解决Excel中文乱码）
        fwrite($output, "\xEF\xBB\xBF");
        
        // 写入基本信息
        fputcsv($output, ['=== 回答基本信息 ===']);
        fputcsv($output, ['回答ID', $answer['id']]);
        fputcsv($output, ['问卷标题', $answer['questionnaire_title']]);
        fputcsv($output, ['IP地址', $answer['respondent_ip']]);
        fputcsv($output, ['回答时间', $answer['created_at']]);
        
        // 添加空行分隔
        fputcsv($output, []);
        
        // 写入问题详情表头
        fputcsv($output, ['=== 问题详情 ===']);
        fputcsv($output, ['问题ID', '问题内容', '问题类型', '回答内容']);
        
        // 写入问题详情
        foreach ($processedDetails as $detail) {
            fputcsv($output, [
                $detail['question_id'],
                $detail['question_text'],
                $detail['question_type'],
                $detail['answer_content']
            ]);
        }
        
        fclose($output);
        exit;

    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'msg' => $e->getMessage(),
            'data' => null
        ]);
    }
}
public function exportData(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        if (empty($_GET['id'])) {
            throw new Exception("缺少回答ID参数", 400);
        }

        $answerId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
        if ($answerId === false || $answerId <= 0) {
            throw new Exception("回答ID必须是正整数", 400);
        }

        // 获取回答详情 - 使用DISTINCT避免重复
        $stmt = $this->conn->prepare("
            SELECT DISTINCT
                ad.question_id, q.content as question_text, 
                q.type as question_type, q.options as question_options,
                ad.answer_content,
                q.is_name, q.is_date
            FROM answer_details ad
            JOIN questions q ON ad.question_id = q.id
            WHERE ad.answer_id = :answer_id
            ORDER BY q.sort_order ASC
        ");
        $stmt->execute([':answer_id' => $answerId]);
        $details = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 获取回答基本信息
        $answer = $this->getAnswer($answerId, $userId);
        if (!$answer || empty($details)) {
            throw new Exception("回答不存在或无权查看", 404);
        }

        // 处理选择题的选项值
        $processedDetails = [];
        foreach ($details as $detail) {
            if (in_array($detail['question_type'], ['radio', 'check']) && !empty($detail['question_options'])) {
                $options = json_decode($detail['question_options'], true);
                if ($options) {
                    if ($detail['question_type'] === 'radio') {
                        $detail['answer_content'] = $options[$detail['answer_content']] ?? $detail['answer_content'];
                    } else {
                        $selectedOptions = explode(',', $detail['answer_content']);
                        $translatedOptions = [];
                        foreach ($selectedOptions as $option) {
                            $translatedOptions[] = $options[$option] ?? $option;
                        }
                        $detail['answer_content'] = implode(', ', $translatedOptions);
                    }
                }
            }
            $processedDetails[] = $detail;
        }

        // 生成标题
        $respondentNameParts = [];
        foreach ($processedDetails as $detail) {
            if ($detail['is_name']) {
                $respondentNameParts[] = $detail['answer_content'];
            }
        }
        $title = '回答_' . $answerId . '_' . 
                (empty($respondentNameParts) ? '匿名用户' : implode('_', $respondentNameParts));
        $title = preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '_', $title);

        // 构建CSV内容
        $csvData = [];
        
        // 添加基本信息
        $csvData[] = ['=== 回答基本信息 ==='];
        $csvData[] = ['回答ID', $answer['id']];
        $csvData[] = ['问卷标题', $answer['questionnaire_title']];
        $csvData[] = ['IP地址', $answer['respondent_ip']];
        $csvData[] = ['回答时间', $answer['created_at']];
        
        // 解析respondent_info
        $respondentInfo = json_decode($answer['respondent_info'], true);
        if ($respondentInfo) {
            $csvData[] = ['用户代理', $respondentInfo['user_agent'] ?? ''];
            $csvData[] = ['来源页面', $respondentInfo['referer'] ?? ''];
        }
        
        // 添加空行分隔
        $csvData[] = [];
        $csvData[] = ['=== 问题详情 ==='];
        $csvData[] = ['问题内容', '回答内容'];
        
        // 添加问题详情（确保所有问题都被处理）
        foreach ($processedDetails as $detail) {
            $csvData[] = [
                $detail['question_text'],
                $detail['answer_content']
            ];
        }

        // 返回JSON格式
        echo json_encode([
            'code' => 200,
            'msg' => 'CSV数据生成成功',
            'data' => [
                'csv_data' => $csvData,
                'file_name' => $title . '.csv',
                'answer_info' => [
                    'id' => $answer['id'],
                    'questionnaire_title' => $answer['questionnaire_title']
                ]
            ]
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'msg' => $e->getMessage(),
            'data' => null
        ]);
    }
}

/**
 * 将数组转换为CSV字符串
 */
private function generateCSVString(array $data): string {
    $output = fopen('php://temp', 'r+');
    
    // 写入BOM头（解决Excel中文乱码）
    fwrite($output, "\xEF\xBB\xBF");
    
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    
    rewind($output);
    $csv = stream_get_contents($output);
    fclose($output);
    
    return $csv;
}
    /**
     * 导出问卷所有回答为ZIP压缩包
     */
    public function exportAll(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['questionnaire_id'])) {
                throw new Exception("缺少问卷ID参数", 400);
            }

            $questionnaireId = filter_var($_GET['questionnaire_id'], FILTER_VALIDATE_INT);
            if ($questionnaireId === false || $questionnaireId <= 0) {
                throw new Exception("问卷ID必须是正整数", 400);
            }

            // 检查问卷是否存在且属于当前用户
            $questionnaire = $this->getQuestionnaireForUser($questionnaireId, $userId);
            if (!$questionnaire) {
                throw new Exception("问卷不存在或无权查看", 404);
            }

            // 获取该问卷的所有回答ID
            $stmt = $this->conn->prepare("
                SELECT id FROM answers 
                WHERE questionnaire_id = :questionnaire_id
                ORDER BY created_at DESC
            ");
            $stmt->execute([':questionnaire_id' => $questionnaireId]);
            $answers = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (empty($answers)) {
                throw new Exception("该问卷没有回答记录", 404);
            }

            // 创建临时目录
            $tempDir = sys_get_temp_dir() . '/questionnaire_' . $questionnaireId . '_' . time();
            if (!mkdir($tempDir)) {
                throw new Exception("无法创建临时目录", 500);
            }

            // 生成所有Excel文件
            require_once 'vendor/autoload.php';
            $excelFiles = [];
            
            foreach ($answers as $answer) {
                $detailData = $this->detailInternal($answer['id'], $userId);
                if (!$detailData) continue;

                $answerData = $detailData['answer'];
                $details = $detailData['details'];
                $title = $detailData['title'];

                // 创建Excel文件
                $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
                $sheet = $spreadsheet->getActiveSheet();

                // 设置标题
                $sheet->setTitle('回答详情');
                $sheet->mergeCells('A1:D1');
                $sheet->setCellValue('A1', $title);
                $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);

                // 添加回答基本信息
                $sheet->setCellValue('A3', '回答ID:');
                $sheet->setCellValue('B3', $answerData['id']);
                $sheet->setCellValue('A4', '问卷标题:');
                $sheet->setCellValue('B4', $answerData['questionnaire_title']);
                $sheet->setCellValue('A5', 'IP地址:');
                $sheet->setCellValue('B5', $answerData['respondent_ip']);
                $sheet->setCellValue('A6', '回答时间:');
                $sheet->setCellValue('B6', $answerData['created_at']);

                // 解析respondent_info
                $respondentInfo = json_decode($answerData['respondent_info'], true);
                if ($respondentInfo) {
                    $sheet->setCellValue('A7', '用户代理:');
                    $sheet->setCellValue('B7', $respondentInfo['user_agent'] ?? '');
                    $sheet->setCellValue('A8', '来源页面:');
                    $sheet->setCellValue('B8', $respondentInfo['referer'] ?? '');
                }

                // 添加回答详情表头
                $sheet->setCellValue('A10', '问题ID');
                $sheet->setCellValue('B10', '问题内容');
                $sheet->setCellValue('C10', '问题类型');
                $sheet->setCellValue('D10', '回答内容');
                $sheet->getStyle('A10:D10')->getFont()->setBold(true);

                // 添加回答详情数据
                $row = 11;
                foreach ($details as $detail) {
                    $sheet->setCellValue('A' . $row, $detail['question_id']);
                    $sheet->setCellValue('B' . $row, $detail['question_text']);
                    $sheet->setCellValue('C' . $row, $detail['question_type']);
                    $sheet->setCellValue('D' . $row, $detail['answer_content']);
                    $row++;
                }

                // 设置列宽
                $sheet->getColumnDimension('A')->setWidth(10);
                $sheet->getColumnDimension('B')->setWidth(40);
                $sheet->getColumnDimension('C')->setWidth(15);
                $sheet->getColumnDimension('D')->setWidth(40);

                // 保存Excel文件
                $filename = '回答_' . $answerData['id'] . '_' . preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '_', $title) . '.xlsx';
                $filepath = $tempDir . '/' . $filename;
                
                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filepath);
                
                $excelFiles[] = $filepath;
            }

            // 创建ZIP文件
            $zipFilename = '问卷_' . $questionnaireId . '_' . preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '_', $questionnaire['title']) . '_回答.zip';
            $zipFilepath = sys_get_temp_dir() . '/' . $zipFilename;
            
            $zip = new ZipArchive();
            if ($zip->open($zipFilepath, ZipArchive::CREATE) !== TRUE) {
                throw new Exception("无法创建ZIP文件", 500);
            }
            
            foreach ($excelFiles as $file) {
                $zip->addFile($file, basename($file));
            }
            
            $zip->close();

            // 清理临时文件
            foreach ($excelFiles as $file) {
                unlink($file);
            }
            rmdir($tempDir);

            // 输出ZIP文件
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment;filename="' . $zipFilename . '"');
            header('Cache-Control: max-age=0');
            readfile($zipFilepath);
            unlink($zipFilepath);
            exit;

        } catch (Exception $e) {
            // 清理临时文件
            if (isset($tempDir) && is_dir($tempDir)) {
                array_map('unlink', glob("$tempDir/*"));
                rmdir($tempDir);
            }
            if (isset($zipFilepath) && file_exists($zipFilepath)) {
                unlink($zipFilepath);
            }
            
            throw $e;
        }
    }

    /**
     * 获取回答详情（内部方法）
     */
    private function detailInternal(int $answerId, int $userId): ?array {
        // 获取回答基本信息
        $answer = $this->getAnswer($answerId, $userId);
        if (!$answer) {
            return null;
        }

        // 获取回答详情
        $stmt = $this->conn->prepare("
            SELECT 
                ad.id, ad.question_id, q.content as question_text, 
                q.type as question_type, ad.answer_content,
                q.is_name, q.is_date
            FROM answer_details ad
            JOIN questions q ON ad.question_id = q.id
            WHERE ad.answer_id = :answer_id
            ORDER BY q.sort_order ASC
        ");
        $stmt->execute([':answer_id' => $answerId]);
        $details = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 获取回答者名称（从is_name标记的问题中获取）
        $respondentName = '匿名用户';
        foreach ($details as $detail) {
            if ($detail['is_name']) {
                $respondentName = $detail['answer_content'];
                break;
            }
        }

        return [
            'answer' => $answer,
            'details' => $details,
            'title' => $respondentName . ' - ' . $answer['questionnaire_title']
        ];
    }

    /**
     * 获取回答信息（内部方法）
     */
    private function getAnswer(int $id, int $userId): ?array {
        $stmt = $this->conn->prepare("
            SELECT 
                a.id, a.questionnaire_id, qn.title as questionnaire_title,
                a.respondent_ip, a.respondent_info, a.created_at
            FROM answers a
            JOIN questionnaires qn ON a.questionnaire_id = qn.id
            WHERE a.id = :id AND qn.user_id = :user_id
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $id,
            ':user_id' => $userId
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    /**
     * 获取问卷信息（内部方法）
     */
    private function getQuestionnaireForUser(int $id, int $userId): ?array {
        $stmt = $this->conn->prepare("
            SELECT id, title 
            FROM questionnaires 
            WHERE id = :id AND user_id = :user_id
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $id,
            ':user_id' => $userId
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}